import datetime
from apps.extensions import db
from .cms_post_tag import post_tag
from .cms_category import Category
from .cms_tag import Tag

class Post(db.Model):
    """文章模型"""
    __tablename__ = 'cms_post'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(200), nullable=False, comment='文章标题')
    slug = db.Column(db.String(200), unique=True, nullable=False, comment='文章别名')
    content = db.Column(db.Text, comment='文章内容(Markdown格式)')
    excerpt = db.Column(db.Text, comment='文章摘要')
    type = db.Column(db.String(20), default='rich', comment='文章类型：rich-富文本，markdown-Markdown')
    post_type = db.Column(db.String(20), default='post', comment='类型：post-文章，page-页面')
    featured_image = db.Column(db.String(500), comment='特色图片')
    status = db.Column(db.String(20), default='draft', comment='状态：draft-草稿，published-已发布，private-私有')
    author_id = db.Column(db.Integer, nullable=False, comment='作者ID')
    category_id = db.Column(db.Integer, db.ForeignKey('cms_category.id'), comment='分类ID')
    view_count = db.Column(db.Integer, default=0, comment='浏览次数')
    comment_count = db.Column(db.Integer, default=0, comment='评论数量')
    is_featured = db.Column(db.Boolean, default=False, comment='是否推荐')
    is_sticky = db.Column(db.Boolean, default=False, comment='是否置顶')
    allow_comments = db.Column(db.Boolean, default=True, comment='是否允许评论')
    meta_title = db.Column(db.String(200), comment='SEO标题')
    meta_description = db.Column(db.Text, comment='SEO描述')
    meta_keywords = db.Column(db.String(500), comment='SEO关键词')
    published_at = db.Column(db.DateTime, comment='发布时间')
    deleted = db.Column(db.Boolean, default=False, comment='是否删除')
    created_at = db.Column(db.DateTime, default=datetime.datetime.now(), comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.datetime.now(), onupdate=datetime.datetime.now(), comment='更新时间')
    
    # 与分类的一对多关联
    category = db.relationship('Category', backref=db.backref('posts', lazy='dynamic'))
    
    # 与标签的多对多关联
    tags = db.relationship('Tag', secondary=post_tag, backref=db.backref('posts', lazy='dynamic'))